<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>即时聊天 - 聊天界面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .header {
            background-color: #4CAF50;
            color: white;
            padding: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            font-size: 20px;
        }
        .header .user-info {
            display: flex;
            align-items: center;
        }
        .header .user-name {
            margin-right: 15px;
        }
        .header .admin-link {
            margin-right: 15px;
            color: white;
            text-decoration: none;
            background-color: rgba(255, 255, 255, 0.2);
            padding: 5px 10px;
            border-radius: 4px;
        }
        .header .admin-link:hover {
            background-color: rgba(255, 255, 255, 0.3);
        }
        .header .logout-btn {
            background-color: #f44336;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
        }
        .container {
            display: flex;
            flex: 1;
            overflow: hidden;
        }
        .users-list {
            width: 250px;
            background-color: #fff;
            border-right: 1px solid #ddd;
            overflow-y: auto;
        }
        .user-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #666; /* 默认灰色文本 - 离线状态 */
            opacity: 0.7; /* 默认半透明效果 - 离线状态 */
            background-color: #f9f9f9;
            transition: all 0.3s ease;
        }
        .user-item:hover {
            background-color: #f0f0f0;
        }
        .user-item.active {
            background-color: #e8f5e8;
        }
        .user-status {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: #ccc; /* 灰色 - 离线状态 */
            transition: background-color 0.3s ease;
        }
        .user-status.online {
            background-color: #4CAF50; /* 绿色 - 在线状态 */
            box-shadow: 0 0 5px #4CAF50;
        }
        /* 在线用户高亮显示 - 兼容所有浏览器 */
        .user-item.online-user {
            color: #333; /* 深色文本 */
            opacity: 1; /* 完全不透明 */
            font-weight: 500;
            background-color: #ffffff;
        }
        /* 确保在线状态的图标正确显示 */
        .user-item.online-user .user-status {
            background-color: #4CAF50;
        }
        /* 确保选中状态的在线用户样式 */
        .user-item.online-user.active {
            background-color: #e8f5e8;
        }
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: #fff;
        }
        .chat-header {
            padding: 15px;
            border-bottom: 1px solid #ddd;
            background-color: #f9f9f9;
        }
        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .message {
            max-width: 70%;
            padding: 10px;
            border-radius: 8px;
            word-wrap: break-word;
        }
        .message.sent {
            align-self: flex-end;
            background-color: #dcf8c6;
        }
        .message.received {
            align-self: flex-start;
            background-color: #f0f0f0;
        }
        .message-time {
            font-size: 12px;
            color: #888;
            margin-top: 5px;
            text-align: right;
        }
        .image-container {
            position: relative;
            display: inline-block;
            cursor: pointer;
            transition: transform 0.2s ease;
        }
        .image-container:hover {
            transform: scale(1.02);
        }
        .message-image {
            max-width: 200px;
            max-height: 200px;
            border-radius: 8px;
            display: block;
        }
        .image-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0, 0, 0, 0.6);
            color: white;
            padding: 4px 8px;
            border-radius: 0 0 8px 8px;
            opacity: 0;
            transition: opacity 0.2s ease;
            text-align: center;
            font-size: 12px;
        }
        .image-container:hover .image-overlay {
            opacity: 1;
        }
        /* 图片预览样式 */
        .image-preview {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.9);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        .image-preview-content {
            position: relative;
            max-width: 90%;
            max-height: 90%;
        }
        .image-preview-content img {
            max-width: 100%;
            max-height: 80vh;
            border-radius: 8px;
        }
        .image-preview-close {
            position: absolute;
            top: -35px;
            right: -35px;
            color: white;
            font-size: 30px;
            cursor: pointer;
            background: rgba(0, 0, 0, 0.7);
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            line-height: 1;
        }
        .image-preview-close:hover {
            background: rgba(0, 0, 0, 0.9);
        }
        .message-input-area {
            padding: 20px;
            border-top: 1px solid #ddd;
            background-color: #f9f9f9;
        }
        .input-tools {
            display: flex;
            margin-bottom: 10px;
            gap: 10px;
        }
        .tool-btn {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            padding: 5px 10px;
            border-radius: 4px;
            color: #666;
        }
        .tool-btn:hover {
            background-color: #e0e0e0;
        }
        .emoji-panel {
            display: none;
            position: absolute;
            bottom: 100px;
            left: 20px;
            background-color: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 10px;
            max-width: 300px;
            flex-wrap: wrap;
            gap: 5px;
            z-index: 100;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .emoji {
            font-size: 24px;
            cursor: pointer;
            padding: 5px;
            border-radius: 4px;
        }
        .emoji:hover {
            background-color: #f0f0f0;
        }
        .input-container {
            position: relative;
        }
        #messageInput {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 25px;
            resize: none;
            font-size: 16px;
            min-height: 50px;
            max-height: 150px;
            overflow-y: auto;
        }
        .send-btn {
            position: absolute;
            right: 10px;
            bottom: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 20px;
            cursor: pointer;
        }
        .send-btn:hover {
            background-color: #45a049;
        }
        .no-chat-selected {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            color: #999;
            font-size: 18px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>即时聊天系统</h1>
        <div class="user-info">
            <span class="user-name">欢迎, <%= user.username %></span>
            <% if (user.is_admin) { %>
                <a href="/admin" class="admin-link">管理员面板</a>
            <% } %>
            <form action="/logout" method="POST" style="display: inline;">
                <button type="submit" class="logout-btn">退出登录</button>
            </form>
        </div>
    </div>
    
    <div class="container">
        <div class="users-list" id="usersList">
            <!-- 用户列表将通过JavaScript动态生成 -->
        </div>
        
        <div class="chat-container">
            <div class="chat-header" id="chatHeader">
                <h2>请选择一个用户开始聊天</h2>
            </div>
            
            <div class="chat-messages" id="chatMessages">
                <div class="no-chat-selected">
                    选择一个用户开始对话
                </div>
            </div>
            
            <div class="message-input-area">
                <div class="input-tools">
                    <button class="tool-btn" id="emojiBtn">😊</button>
                    <button class="tool-btn" id="imageBtn">🖼️</button>
                    <input type="file" id="imageUpload" accept="image/*" style="display: none;">
                </div>
                <div class="emoji-panel" id="emojiPanel">
                    <!-- 常用表情 -->
                    <span class="emoji">😊</span>
                    <span class="emoji">😂</span>
                    <span class="emoji">🥰</span>
                    <span class="emoji">😍</span>
                    <span class="emoji">😎</span>
                    <span class="emoji">🤔</span>
                    <span class="emoji">😅</span>
                    <span class="emoji">😭</span>
                    <span class="emoji">🤗</span>
                    <span class="emoji">😘</span>
                    <span class="emoji">👍</span>
                    <span class="emoji">👎</span>
                    <span class="emoji">❤️</span>
                    <span class="emoji">🎉</span>
                    <span class="emoji">🔥</span>
                    <span class="emoji">🤣</span>
                    <span class="emoji">😢</span>
                    <span class="emoji">😡</span>
                    <span class="emoji">🤩</span>
                    <span class="emoji">🤗</span>
                </div>
                <div class="input-container">
                    <textarea id="messageInput" placeholder="输入消息..."></textarea>
                    <button class="send-btn" id="sendBtn" disabled>发送</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="/socket.io/socket.io.js"></script>
    <script>
        const currentUser = { id: <%= user.id %>, username: '<%= user.username %>' };
        let selectedUser = null;
        let socket = io();
        
        // 连接Socket.IO
        socket.on('connect', () => {
            console.log('Connected to server');
            socket.emit('login', currentUser.id);
        });
        
        // 获取用户列表
        function loadUsers() {
            fetch('/api/users')
                .then(response => response.json())
                .then(users => {
                    const usersList = document.getElementById('usersList');
                    usersList.innerHTML = '';
                    
                    users.forEach(user => {
                        const userItem = document.createElement('div');
                        userItem.className = 'user-item';
                        userItem.dataset.userId = user.id;
                        userItem.innerHTML = `
                            <span>${user.username} ${user.is_admin ? '(管理员)' : ''}</span>
                            <span class="user-status" id="status-${user.id}"></span>
                        `;
                        
                        userItem.addEventListener('click', () => {
                            selectUser(user);
                        });
                        
                        usersList.appendChild(userItem);
                    });
                    
                    // 请求在线用户列表
                    socket.emit('get-active-users');
                });
        }
        
        // 选择用户开始聊天
        function selectUser(user) {
            selectedUser = user;
            
            // 更新UI
            document.querySelectorAll('.user-item').forEach(item => {
                item.classList.remove('active');
            });
            document.querySelector(`.user-item[data-user-id="${user.id}"]`).classList.add('active');
            
            document.getElementById('chatHeader').innerHTML = `<h2>与 ${user.username} 聊天</h2>`;
            document.getElementById('chatMessages').innerHTML = '';
            document.getElementById('sendBtn').disabled = false;
            
            // 加载聊天记录
            loadMessages(user.id);
        }
        
        // 加载聊天记录
        function loadMessages(userId) {
            fetch(`/api/messages/${userId}`)
                .then(response => response.json())
                .then(messages => {
                    const chatMessages = document.getElementById('chatMessages');
                    chatMessages.innerHTML = '';
                    
                    messages.forEach(message => {
                        displayMessage(message);
                    });
                    
                    // 滚动到底部
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                });
        }
        
        // 显示消息
        function displayMessage(message) {
            const chatMessages = document.getElementById('chatMessages');
            const isSent = message.sender_id == currentUser.id;
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isSent ? 'sent' : 'received'}`;
            
            // 格式化时间为年月日时分秒
            const date = new Date(message.created_at);
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            const seconds = date.getSeconds().toString().padStart(2, '0');
            const timeString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            
            if (message.message_type === 'image') {
                // 直接使用base64数据作为图片源
                const base64Image = message.content;
                
                messageDiv.innerHTML = `
                    <div class="image-container">
                        <img src="${base64Image}" class="message-image" alt="图片消息" onerror="this.onerror=null; this.src='/images/placeholder.svg'; this.alt='图片加载失败';">
                        <div class="image-overlay">点击查看大图</div>
                    </div>
                    <div class="message-time">${timeString}</div>
                `;
                
                // 添加点击图片预览功能
                const imageContainer = messageDiv.querySelector('.image-container');
                
                imageContainer.addEventListener('click', () => {
                    const preview = document.createElement('div');
                    preview.className = 'image-preview';
                    preview.innerHTML = `
                        <div class="image-preview-content">
                            <span class="image-preview-close">&times;</span>
                            <img src="${base64Image}" alt="图片预览">
                        </div>
                    `;
                    document.body.appendChild(preview);
                    
                    // 关闭预览函数
                    const closePreview = () => {
                        document.body.removeChild(preview);
                        document.removeEventListener('keydown', handleEscKey);
                    };
                    
                    // 处理ESC键
                    const handleEscKey = (e) => {
                        if (e.key === 'Escape') {
                            closePreview();
                        }
                    };
                    
                    // 添加ESC键监听
                    document.addEventListener('keydown', handleEscKey);
                    
                    // 关闭按钮事件
                    preview.querySelector('.image-preview-close').addEventListener('click', closePreview);
                    
                    // 点击空白处关闭预览
                    preview.addEventListener('click', (e) => {
                        if (e.target === preview) {
                            closePreview();
                        }
                    });
                });
            } else {
                messageDiv.innerHTML = `
                    <div>${message.content}</div>
                    <div class="message-time">${timeString}</div>
                `;
            }
            
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
        
        // 发送消息
        function sendMessage() {
            if (!selectedUser) return;
            
            const messageInput = document.getElementById('messageInput');
            const content = messageInput.value.trim();
            
            if (content) {
                socket.emit('send-message', {
                    receiver_id: selectedUser.id,
                    content: content,
                    message_type: 'text'
                });
                
                messageInput.value = '';
                messageInput.style.height = '50px';
            }
        }
        
        // 发送图片
        function sendImage(file) {
            // 检查文件类型
            const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
            if (!validTypes.includes(file.type)) {
                alert('请上传有效的图片文件（JPG、PNG、GIF、WebP）');
                return;
            }
            
            // 检查文件大小（10MB限制）
            if (file.size > 10 * 1024 * 1024) {
                alert('图片文件不能超过10MB');
                return;
            }
            
            const formData = new FormData();
            formData.append('image', file);
            
            // 显示上传中提示
            const loadingMessage = createLoadingMessage();
            
            fetch('/api/upload-image', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('上传失败，服务器返回错误');
                }
                return response.json();
            })
            .then(data => {
                // 移除上传中提示
                removeLoadingMessage(loadingMessage);
                
                if (data.base64) {
                    socket.emit('send-message', {
                        receiver_id: selectedUser.id,
                        content: data.base64,
                        message_type: 'image'
                    });
                } else if (data.error) {
                    alert('上传失败: ' + data.error);
                }
            })
            .catch(error => {
                // 移除上传中提示并显示错误
                removeLoadingMessage(loadingMessage);
                console.error('图片上传错误:', error);
                alert('图片上传失败，请重试');
            });
        }
        
        // 创建上传中提示
        function createLoadingMessage() {
            const chatMessages = document.getElementById('chatMessages');
            const loadingDiv = document.createElement('div');
            loadingDiv.className = 'message sent loading';
            loadingDiv.innerHTML = '<div>图片上传中...</div>';
            chatMessages.appendChild(loadingDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
            return loadingDiv;
        }
        
        // 移除上传中提示
        function removeLoadingMessage(loadingElement) {
            if (loadingElement && loadingElement.parentNode) {
                loadingElement.parentNode.removeChild(loadingElement);
            }
        }
        
        // 自动退出登录功能
        let inactivityTimer;
        const INACTIVITY_TIMEOUT = 60 * 60 * 1000; // 1小时
        
        function resetInactivityTimer() {
            clearTimeout(inactivityTimer);
            inactivityTimer = setTimeout(() => {
                // 自动退出登录
                alert('由于您长时间未操作，系统将自动退出登录');
                // 创建隐藏表单提交POST请求
                const logoutForm = document.createElement('form');
                logoutForm.action = '/logout';
                logoutForm.method = 'POST';
                document.body.appendChild(logoutForm);
                logoutForm.submit();
            }, INACTIVITY_TIMEOUT);
        }
        
        // 监听用户活动
        function setupInactivityTracking() {
            // 重置定时器的事件类型
            const activityEvents = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
            
            activityEvents.forEach(event => {
                document.addEventListener(event, resetInactivityTimer, false);
            });
            
            // 初始启动定时器
            resetInactivityTimer();
        }
        
        // 事件监听器
        document.addEventListener('DOMContentLoaded', () => {
            loadUsers();
            setupInactivityTracking();
            
            // 发送按钮点击
            document.getElementById('sendBtn').addEventListener('click', sendMessage);
            
            // 回车发送消息
            document.getElementById('messageInput').addEventListener('keydown', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });
            
            // 自动调整输入框高度
            document.getElementById('messageInput').addEventListener('input', (e) => {
                e.target.style.height = '50px';
                e.target.style.height = (e.target.scrollHeight > 150 ? 150 : e.target.scrollHeight) + 'px';
            });
            
            // 表情按钮
            const emojiBtn = document.getElementById('emojiBtn');
            const emojiPanel = document.getElementById('emojiPanel');
            
            emojiBtn.addEventListener('click', () => {
                emojiPanel.style.display = emojiPanel.style.display === 'flex' ? 'none' : 'flex';
            });
            
            // 点击其他地方关闭表情面板
            document.addEventListener('click', (e) => {
                if (!emojiBtn.contains(e.target) && !emojiPanel.contains(e.target)) {
                    emojiPanel.style.display = 'none';
                }
            });
            
            // 选择表情
            document.querySelectorAll('.emoji').forEach(emoji => {
                emoji.addEventListener('click', () => {
                    const messageInput = document.getElementById('messageInput');
                    messageInput.value += emoji.textContent;
                    messageInput.focus();
                    emojiPanel.style.display = 'none';
                });
            });
            
            // 图片上传按钮
            document.getElementById('imageBtn').addEventListener('click', () => {
                document.getElementById('imageUpload').click();
            });
            
            document.getElementById('imageUpload').addEventListener('change', (e) => {
                if (e.target.files && e.target.files[0]) {
                    sendImage(e.target.files[0]);
                    e.target.value = '';
                }
            });
            
            // 粘贴图片
            document.getElementById('messageInput').addEventListener('paste', (e) => {
                const items = (e.clipboardData || e.originalEvent.clipboardData).items;
                for (let item of items) {
                    if (item.kind === 'file') {
                        const file = item.getAsFile();
                        if (file.type.indexOf('image/') === 0) {
                            e.preventDefault();
                            sendImage(file);
                        }
                    }
                }
            });
        });
        
        // 标题闪烁功能
        let isOriginalTitle = true;
        let flashInterval;
        const originalTitle = document.title;
        
        function startTitleFlash(message) {
            // 只有当页面不在焦点时才闪烁
            if (document.hidden) {
                let notificationCount = 0;
                clearInterval(flashInterval);
                
                flashInterval = setInterval(() => {
                    if (isOriginalTitle) {
                        document.title = `【新消息】${message.sender_name}: ${message.content.substring(0, 20)}...`;
                        notificationCount++;
                    } else {
                        document.title = originalTitle;
                    }
                    isOriginalTitle = !isOriginalTitle;
                    
                    // 闪烁10次后停止
                    if (notificationCount >= 10) {
                        stopTitleFlash();
                        // 保持提示状态
                        document.title = `【新消息】${originalTitle}`;
                    }
                }, 1000);
            }
        }
        
        function stopTitleFlash() {
            clearInterval(flashInterval);
            document.title = originalTitle;
            isOriginalTitle = true;
        }
        
        // 监听页面焦点事件
        document.addEventListener('visibilitychange', () => {
            if (!document.hidden) {
                stopTitleFlash();
            }
        });
        
        // Socket.IO 事件
        socket.on('receive-message', (message) => {
            // 如果是当前聊天的消息，直接显示
            if (selectedUser && (message.sender_id == selectedUser.id || message.receiver_id == selectedUser.id)) {
                displayMessage(message);
            } else {
                // 否则提示有新消息
                const userItem = document.querySelector(`.user-item[data-user-id="${message.sender_id}"]`);
                if (userItem) {
                    userItem.style.backgroundColor = '#e3f2fd';
                }
                
                // 启动标题闪烁提醒
                startTitleFlash(message);
            }
        });
        
        // 更新用户在线状态
        socket.on('active-users', (userIds) => {
            userIds.forEach(userId => {
                updateUserOnlineStatus(userId, true);
            });
        });
        
        socket.on('user-online', (userId) => {
            updateUserOnlineStatus(userId, true);
        });
        
        socket.on('user-offline', (userId) => {
            updateUserOnlineStatus(userId, false);
        });
        
        // 更新用户项的在线状态样式
        function updateUserOnlineStatus(userId, isOnline) {
            const statusElement = document.getElementById(`status-${userId}`);
            const userItem = document.querySelector(`.user-item[data-user-id="${userId}"]`);
            
            if (statusElement) {
                if (isOnline) {
                    statusElement.classList.add('online');
                } else {
                    statusElement.classList.remove('online');
                }
            }
            
            // 为了确保跨浏览器兼容性，直接更新用户项的类
            if (userItem) {
                if (isOnline) {
                    userItem.classList.add('online-user');
                } else {
                    userItem.classList.remove('online-user');
                }
            }
        }
    </script>
</body>
</html>